﻿CREATE PROCEDURE [dbo].[CreateErrorLog]
	@ErrorType NVARCHAR(500),
	@ErrorAction NVARCHAR(25),
	@TableName NVARCHAR(50),
	@Metadata XML
AS
BEGIN
	BEGIN TRY
		SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
		SET NOCOUNT ON;
		DECLARE @tmp TABLE (pk BIGINT);
		DECLARE @id BIGINT;

		INSERT INTO [Reporting].[vwErrorLog] (ErrorType, ErrorAction, TableName, Metadata, CreatedBy, DateCreated, DateDeleted, VersionDate, VersionUser)
		OUTPUT Inserted.ErrorLogID INTO @tmp
		VALUES (@ErrorType, @ErrorAction, @TableName, @Metadata, SYSTEM_USER, GETDATE(), NULL, GETDATE(), SYSTEM_USER);

		SELECT @id = pk FROM @tmp
		RETURN 0
	END TRY
	BEGIN CATCH
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;
		DECLARE @ErrorTimeStamp DATETIME;
		DECLARE @ErrAction NVARCHAR(25);
		DECLARE @report XML;

		SELECT	@ErrorMessage   = ERROR_MESSAGE(),
				@ErrorSeverity  = ERROR_SEVERITY(),
				@ErrorState     = ERROR_STATE(),
				@ErrorTimeStamp = GETDATE(),
				@ErrAction      = 'CREATE';				

		SET @report = (SELECT	@ErrorMessage	AS ErrorMessage,
								@ErrAction	AS ErrorAction,
								@ErrorSeverity	AS ErrorSeverity,
								@ErrorState		AS ErrorState,
								@ErrorTimeStamp AS ErrorTimestamp 
								FOR XML PATH('Error'), 
								TYPE, 
								ROOT('ErrorLog'));		

		EXEC dbo.CreateErrorLog @ErrorType = 'ERROR', @ErrorAction = @ErrAction, @TableName = 'ErrorLog', @Metadata = @report;
	END CATCH
END